from zope.interface import implements, Interface

#from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize
#from zope.i18n.interfaces import ITranslationDomain
#from zope.component import queryUtility
from zope.component import getUtility
from Products.CMFCore.interfaces import ISiteRoot
from Products.AdvancedQuery import Eq, Between, Le

from my315ok.fangcan import fangcanMessageFactory as _
from my315ok.fangcan.browser.secondhouse_listsview import secondhouse_listsView
from my315ok.fangcan.interfaces import Ihouse,Isubdistrict


class Isubdistrict_listsView(Interface):
    """
    subdistrict_lists view interface
    """

    def test():
        """ test method"""


class subdistrict_listsView(secondhouse_listsView):
    """
    subdistrict_lists browser view
    """
    implements(Isubdistrict_listsView)

    def averageprice(self,brain,):
        category="secondhand house"
        bns = self.get_brains(brain,category)
        total = len(bns)
        if total == 0:
            return "0"
        sum = 0
        for bn in bns:
            sum = sum + bn.Sale_unitprice
        average = sum/total
        average = '%1.2f' % average
        return average
        
        
    def secondhandamount(self,brain,category="1"):
        bns = self.get_brains(brain,category)
        return len(bns)
    def newhouseamount(self,brain,category="0"):
        bns = self.get_brains(brain,category)
        return len(bns)
    def rentamount(self,brain,category="2"):
        bns = self.get_brains(brain,category)
        return len(bns)
        
#    def getGreening_ratio(self,brain):
#        
#        ratio = self.context.getCapacity_ratio()
#        ratio = ratio * 100
#        if ratio == None:
#            return ""
#        out = "%1.2f" % ratio + "%"
#        return out
        
    
    @memoize
    def get_brains(self,brain,category):
        """ Fetches the last contract (or letter) of the
        employee (last in the meaning 'The one that ends the later'
        not 'The last one created'.)
        """
#        contentFilter = {'portal_type': ['Contract', 'Letter']}

#        import pdb
#        pdb.set_trace()
#        context = aq_inner(self.context)
#        tools = getMultiAdapter((context, self.request), name=u'plone_tools')

        name = brain.Title
        pc = getToolByName(self.context, 'portal_catalog')
        brains = pc(object_provides=Ihouse.__identifier__,
                             category=category,
                             Estate=name,
                             review_status='published',
                             sort="modified",
                             sort_order='reverse'
                             )
#        brains = self.getFolderContents(contentFilter=contentFilter)
        if not brains:
            return []
        return brains
    
    def rentamount_url(self,brain):
        return ""
    
    def secondhandamount_url(self,brain):        
        """"""
        category = "secondhand house"
        portal_url = self.portal.absolute_url()
        url = "%s/ershou/@@secondhouse_lists_view?category=%s&Estate=%s" %(portal_url,category,brain.Title)
        
        return url
    def query(self):
        """
        compose secondhand house query string
        """
        portal = getUtility(ISiteRoot)
        cat = getToolByName(portal, 'portal_catalog')
#        cat = getToolByName(context, 'portal_catalog')
        aq = cat.makeAdvancedQuery({'object_provides' : Isubdistrict.__identifier__, 'review_state' : 'published'})
        raw = self.request["QUERY_STRING"]

        if "SearchableText" in self.request.form.keys():
            term = self.request.form["SearchableText"]
            term = term.strip()
            if len(term)!=0:
                query = Eq("SearchableText",term) | Eq('Description',term)
                return query               
        
        elif len(raw) != 0:
            phase = raw.split("&")
            for st2 in phase:                
                st = st2.split("=")
                pa = st[0]
                val = st[-1]            
                if "-" in val:
#                op = Between
                    low = val.split("-")[0]
                    hight = val.split("-")[-1]
                    query = Between(pa,float(low),float(hight))                
                else:
#                op = Eq
                    query = Eq(pa, val)
#                aq = query
                aq &= query 
            return query
        else:
            return aq